package system

import (
	"5title_gin/global"
	"5title_gin/internal/model/system/dept"
	"5title_gin/pkg/db/crud"
	"5title_gin/pkg/tree"
	"strings"
)

type DeptService struct {
	crud *crud.CRUD[dept.SysDept]
}

func NewDeptService() *DeptService {
	return &DeptService{
		crud: crud.NewCRUD[dept.SysDept](global.DB),
	}
}

// CreateDept 创建部门
func (s *DeptService) CreateDept(bo dept.SysDeptBo) (string, error) {
	if strings.TrimSpace(bo.DeptName) == "" {
		return "部门名称不能为空！", nil
	}
	if bo.ParentId == 0 {
		return "必须指定有效的父部门ID", nil
	}
	result := dept.SysDept{
		CreateBy:     bo.CreateBy,
		CreateDept:   bo.CreateDept,
		DeptCategory: bo.DeptCategory,
		DeptName:     bo.DeptName,
		DeptSort:     bo.DeptSort,
		Email:        bo.Email,
		Leader:       bo.Leader,
		ParentId:     bo.ParentId,
		Phone:        bo.Phone,
	}
	if err := s.crud.Create(&result); err != nil {
		return "创建失败", err
	}
	return "部门创建成功！", nil
}

// GetDeptList 获取部门列表
func (s *DeptService) GetDeptList() ([]*dept.SysDeptVo, error) {
	list, err := s.crud.GetAll().Find()
	// 将部门列表转换为树形结构
	deptTree := dept.GetDepartmentTree(list)
	if err != nil {
		return nil, err
	}
	return deptTree, nil
}

// GetDeptInfo 获取部门信息
func (s *DeptService) GetDeptInfo(id uint) (*dept.SysDept, error) {
	result, err := s.crud.GetByID(id)
	if err != nil {
		return &dept.SysDept{}, err
	}
	return result, nil
}

// UpdateDept 更新部门信息
func (s *DeptService) UpdateDept(bo dept.SysDeptBo) error {
	result := dept.SysDept{
		CreateBy:     bo.CreateBy,
		CreateDept:   bo.CreateDept,
		DeptCategory: bo.DeptCategory,
		DeptName:     bo.DeptName,
		DeptSort:     bo.DeptSort,
		Email:        bo.Email,
		Leader:       bo.Leader,
		ParentId:     bo.ParentId,
		Phone:        bo.Phone,
	}
	return s.crud.Update(&result)
}

// DeleteDept 删除部门
func (s *DeptService) DeleteDept(id uint) error {
	return s.crud.DeleteByID(id)
}

// GetDeptTreeSelector 获取部门树选择器数据
func (s *DeptService) GetDeptTreeSelector() ([]*dept.DeptTreeModel, error) {
	// 使用仓库层获取部门列表
	list, err := s.crud.GetAll().Find()
	if err != nil {
		return nil, err
	}
	// 转换为DeptTreeModel
	deptModels := make([]*dept.DeptTreeModel, len(list))
	for i, d := range list {
		deptModels[i] = &dept.DeptTreeModel{
			ID:       d.ID,
			Name:     d.DeptName,
			ParentID: d.ParentId,
			Children: []*dept.DeptTreeModel{},
		}
	}

	// 使用tree工具构建树形结构
	treeBuilder := tree.NewTree(deptModels)
	return treeBuilder.BuildTree(0), nil

}
